﻿using Common;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DLL;
using NursingFormSystem.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace NursingFormSystem
{
    public partial class HealthEducation : Form
    {
        private NursingFormSystem.DNNursingService.BNNursingDocsSystem bnService = new NursingFormSystem.DNNursingService.BNNursingDocsSystem();
        private Tb_User LoginUser;
        private string[] Patientinfo;
        private string[] UserParam;
        private RepositoryItemCheckEdit CheckItem = new RepositoryItemCheckEdit();
        public HealthEducation(string[] userParam, string[] patientinfo)
        {
            InitializeComponent();
            this.UserParam = userParam;
            this.Patientinfo = patientinfo;
            InitLoginUser(UserParam);
            BindControl();
            BindInfo();
        }

        DataRowCollection PrintTempList;
        private void BindControl()
        {
            CmbPrintTemp.SelectedIndex = -1;
            DataSet ds = SqlHelper.ExecuteDataset("SELECT  DiseasesGuid,TemplateName  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduDiseases](NOLOCK)  where DepartmentID like '%" + LoginUser.DepartmentCode + "%'", CommandType.Text);
            if (ds == null || ds.Tables.Count <= 0) return;
            DataTable tb = ds.Tables[0];
            if (tb == null || tb.Rows.Count <= 0) return;
            PrintTempList = tb.Rows;
            foreach (DataRow row in PrintTempList)
            {
                CmbPrintTemp.Items.Add(row["TemplateName"]);
            }
            if (CmbPrintTemp.Items.Count > 0)
                CmbPrintTemp.SelectedIndex = 0;
        }
        public Tb_User InitLoginUser(string[] UserParam)
        {
            LoginUser = new Tb_User();
            LoginUser.UserId = UserParam[0];
            LoginUser.UserName = UserParam[1];
            LoginUser.DepartmentCode = UserParam[2];
            LoginUser.DepartmentName = UserParam[3];
            LoginUser.JobTitle = UserParam[4];
            LoginUser.PositionTitle = UserParam[5];
            return LoginUser;
        }

        #region 加载数据
        public void BindInfo()
        {
            //绑定数据
            string PatientID = Patientinfo[0];
            string VisitID = Patientinfo[1];
            string BaseSelect = @"  SELECT b.*, CASE WHEN b.ClassName LIKE '入院%' THEN 1 WHEN b.ClassName LIKE '住院%' THEN 2 ELSE 3 END AS SeqNo FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduBase] b(NOLOCK) WHERE PatientID ='{0}' AND VisitID ='{1}' ORDER BY SeqNo ASC , b.ProjectContentID ASC ";
            BaseSelect = string.Format(BaseSelect, PatientID, VisitID);
            DataSet ds2 = SqlHelper.ExecuteDataset(BaseSelect, CommandType.Text);
            if (ds2 == null) return;
            DataTable BaseTemp = ds2.Tables[0];
            BaseTemp.Columns.Add("勾选", Type.GetType("System.Boolean"));
            BaseTemp.Columns["勾选"].DefaultValue = Boolean.FalseString;
            BaseTemp.Columns["勾选"].SetOrdinal(0);
            BaseTemp.Columns["ClassName"].SetOrdinal(1);
            BaseTemp.Columns["ProjectName"].SetOrdinal(2);
            BaseTemp.Columns["EduNurse"].SetOrdinal(3);
            BaseTemp.Columns["EduDate"].SetOrdinal(4);
            BaseTemp.Columns["EduMethods"].SetOrdinal(5);
            BaseTemp.Columns["EduObj"].SetOrdinal(6);
            BaseTemp.Columns["Evaluation"].SetOrdinal(7);
            BaseTemp.Columns["EvaluationDate"].SetOrdinal(8);
            BaseTemp = UpdateDataTable(BaseTemp);
            gridControl1.DataSource = BaseTemp;
            //重新设定控件属性
            gridView1.OptionsMenu.EnableColumnMenu = false;
            gridView1.OptionsCustomization.AllowSort = false;
            gridView1.OptionsView.ShowGroupPanel = false;
            gridView1.OptionsBehavior.Editable = true;
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.Columns["DiseasesGuid"].Visible = false;
            gridView1.Columns["ProjectGuid"].Visible = false;
            gridView1.Columns["ClassGuid"].Visible = false;
            gridView1.Columns["id"].Visible = false;
            gridView1.Columns["DepartmentName"].Visible = false;
            gridView1.Columns["DepartmentID"].Visible = false;
            gridView1.Columns["DiseasesName"].Visible = false;
            gridView1.Columns["DiseasesGuid"].Visible = false;
            gridView1.Columns["ProjectGuid"].Visible = false;
            gridView1.Columns["ProjectContent"].Visible = false;
            gridView1.Columns["ProjectContentID"].Visible = false;
            gridView1.Columns["ClassGuid"].Visible = false;
            gridView1.Columns["PatientName"].Visible = false;
            gridView1.Columns["PatientID"].Visible = false;
            gridView1.Columns["EduNurseID"].Visible = false;
            gridView1.Columns["TemplateID"].Visible = false;
            gridView1.Columns["TemplateName"].Visible = false;
            gridView1.Columns["VisitID"].Visible = false;
            gridView1.Columns["SeqNo"].Visible = false;
            gridView1.Columns["ClassName"].Caption = "分类";
            gridView1.Columns["ProjectName"].Caption = "项目";
            gridView1.Columns["EduObj"].Caption = "宣教对象";
            gridView1.Columns["EduMethods"].Caption = "宣教方式";
            gridView1.Columns["EduNurse"].Caption = "宣教人";
            gridView1.Columns["EvaluationDate"].Caption = "评价时间";
            gridView1.Columns["EduDate"].Caption = "宣教时间";
            gridView1.Columns["Evaluation"].Caption = "评价";
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.RowSelect;
            gridView1.OptionsCustomization.AllowColumnMoving = false;
            gridView1.OptionsView.AllowCellMerge = true;
            for (int i = 0; i < gridView1.Columns.Count; i++)
            {
                if (gridView1.Columns[i].Name != "col勾选")
                {
                    gridView1.Columns[i].OptionsColumn.AllowEdit = false;
                }
                if (gridView1.Columns[i].Name == "col勾选" || gridView1.Columns[i].Name == "colSeqNo" || gridView1.Columns[i].Name == "colEduMethods" || gridView1.Columns[i].Name == "colEduObj" || gridView1.Columns[i].Name == "colEduNurse" || gridView1.Columns[i].Name == "colEvaluation" || gridView1.Columns[i].Name == "colEvaluationDate" || gridView1.Columns[i].Name == "colEduDate")
                {
                    gridView1.Columns[i].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                }
                gridView1.Columns[i].Width = Convert.ToInt32(gridView1.Columns[i].Width * 1.3);
            }
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.SetRowCellValue(i, gridView1.Columns["EduDate"], Convert.ToDateTime(Convert.ToDateTime(gridView1.GetDataRow(i)["EduDate"].ToString())).ToString("yyyy-MM-dd HH:mm"));
                gridView1.SetRowCellValue(i, gridView1.Columns["EvaluationDate"], Convert.ToDateTime(Convert.ToDateTime(gridView1.GetDataRow(i)["EvaluationDate"].ToString())).ToString("yyyy-MM-dd HH:mm"));
            }
            gridView1.BestFitColumns();
            gridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            gridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;//是否显示过滤面板
            gridView1.OptionsCustomization.AllowFilter = false;//是否允许过滤
            gridView1.Columns[0].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            gridView1.Columns[1].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            gridView1.Columns[2].Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            gridView1.Columns[0].Caption = " ";

            RepositoryItemMemoEdit repoMemo = new RepositoryItemMemoEdit();
            repoMemo.WordWrap = true;
            repoMemo.AutoHeight = true;
            this.gridControl1.RepositoryItems.Add(repoMemo);
            gridView1.Columns[1].ColumnEdit = repoMemo;
            gridView1.Columns[2].ColumnEdit = repoMemo;
            gridView1.OptionsView.RowAutoHeight = true;
            gridView1.Columns[0].Width = 25;
            gridView1.Columns[0].MinWidth = 25;
            gridView1.Columns[0].MaxWidth = 25;
            gridView1.Columns[1].Width = 60;
            gridView1.Columns[1].MinWidth = 60;
            gridView1.Columns[1].MaxWidth = 60;
            gridView1.Columns[2].Width = 240;
            gridView1.Columns[2].MinWidth = 240;
            gridView1.Columns[2].MaxWidth = 365;
        }
        private void gridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            GridView _view = sender as GridView;
            Draw.DrawHeaderCheckBox(gridView1, CheckItem, "勾选", e);
        }
        #endregion

        #region 新增健康宣教事件
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            NewHealetEducation F2 = new NewHealetEducation(UserParam,  Patientinfo);
            F2.ShowDialog(this);
            BindInfo();
        }
        #endregion

        #region 修改datatable的datatype，让其可以显示完整时间
        /// <summary>
        ///当DataTable中有值时，是不允许修改列的DataType
        /// 修改数据表DataTable某一列的数据类型和记录值
        /// </summary>
        /// <param name="argDataTable">数据表DataTable</param>
        /// <returns>数据表DataTable</returns>
        private DataTable UpdateDataTable(DataTable argDataTable)
        {
            DataTable dtResult = new DataTable(); //克隆表结构
            dtResult = argDataTable.Clone();
            foreach (DataColumn col in dtResult.Columns)
            {
                if (col.ColumnName == "EvaluationDate" || col.ColumnName == "EduDate")
                {
                    col.DataType = typeof(System.String);
                }
            }

            foreach (DataRow row in argDataTable.Rows)
            {
                dtResult.ImportRow(row);
            }
            return dtResult;

        }
        #endregion

        #region 批量修改时间
        private void ButtonChangeTime_Click(object sender, EventArgs e)
        {
            string time = string.Empty;
            string value = string.Empty;
            int Checked = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    Checked++;
                }
            }
            if (Checked == 0)
            {
                XtraMessageBox.Show("没有勾选任何条目");
                return;
            }
            SetEduTime setTime = new SetEduTime();
            setTime.ShowDialog();
            if (setTime.DialogResult != DialogResult.OK)
                return;
            time = setTime.time;
            string[] idArray = new string[Checked];
            for (int i = 0, j = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    idArray[j] = gridView1.GetDataRow(i)["id"].ToString();
                    j++;
                }
            }
            string ids = string.Empty;
            foreach (var item in idArray)
            {
                ids += item + ",";
            }
            ids = ids.Trim(',');
            string sql = @"use BNNursingDocsSystem_Develop ; update HealthEduBase set [EduDate] = '{0}',[EvaluationDate] = '{0}' WHERE id IN ({1}) ";
            sql = string.Format(sql, time, ids);
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
            XtraMessageBox.Show("更新成功");
            BindInfo();
        }
        #endregion

        #region 编辑事件
        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            string value = string.Empty;
            int Checked = 0;
            string DiseasesGuid = string.Empty;
            string ProjectGuid = string.Empty;
            string ClassGuid = string.Empty;
            string id = string.Empty;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    Checked++;
                    DiseasesGuid = gridView1.GetDataRow(i)["DiseasesGuid"].ToString();
                    ProjectGuid = gridView1.GetDataRow(i)["ProjectGuid"].ToString();
                    ClassGuid = gridView1.GetDataRow(i)["ClassGuid"].ToString();
                    id = gridView1.GetDataRow(i)["id"].ToString();
                    if (Checked > 1) break;

                }
            }
            if (Checked <= 0)
            {
                XtraMessageBox.Show("没有勾选任何条目");
                return;
            }
            if (Checked > 1)
            {
                XtraMessageBox.Show("目前只支持单独一条宣教内容的修改");
                return;
            }
            ChangeHealthEducation F2 = new ChangeHealthEducation(UserParam, Patientinfo[0], Patientinfo[1], DiseasesGuid, ProjectGuid, ClassGuid, id);
            F2.ShowDialog(this);
            BindInfo();
        }
        #endregion

        #region 删除事件
        private void ButtonDelete_Click(object sender, EventArgs e)
        {
            string value = string.Empty;
            int Checked = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    Checked++;
                }
            }
            if (Checked == 0)
            {
                XtraMessageBox.Show("没有勾选任何条目");
                return;
            }
            DialogResult Delete = XtraMessageBox.Show("确定要删除勾选的" + Checked + "条数据吗吗？", "删除询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (Delete != DialogResult.OK) return;
            string[] idArray = new string[Checked];
            for (int i = 0, j = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    idArray[j] = gridView1.GetDataRow(i)["id"].ToString();
                    j++;
                }
            }
            string ids = string.Empty;
            foreach (var item in idArray)
            {
                ids += item + ",";
            }
            ids = ids.Trim(',');
            string sql = @"delete from HealthEduBase where id in ({0})";
            sql = string.Format(sql, ids);
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
            XtraMessageBox.Show("删除成功");
            BindInfo();
        }
        #endregion

        #region 打印事件
        private void ButtonPrint_Click(object sender, EventArgs e)
        {
            if (Patientinfo.Length <= 0 || string.IsNullOrEmpty(Patientinfo[1])) return;
            if (CmbPrintTemp.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择模板");
                return;
            }
            PatientInfoView P = new PatientInfoView();
            P.NURSE_CELL_NAME = LoginUser.DepartmentName;
            P.PATIENT_NAME = Patientinfo[2];
            P.VISIT_ID = Convert.ToInt32(Patientinfo[1]);
            P.BED_NO = Patientinfo[5];
            P.PATIENT_ID = Patientinfo[0];
            P.SEX = Patientinfo[3];
            if (P.SEX == "1") P.SEX = "男";
            if (P.SEX == "2") P.SEX = "女";
            string value = string.Empty;
            int Checked = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                value = gridView1.GetDataRow(i)["勾选"].ToString();
                if (value == "True")
                {
                    Checked++;
                }
            }
            string sql = @"SELECT id, DepartmentID, DiseasesName, DiseasesGuid, ProjectName, ProjectGuid, ProjectContent, ProjectContentID, ClassName, ClassGuid, EduMethods, PatientName, PatientID, EduNurse, EduDate, Evaluation, EvaluationDate, EduNurseID, EduObj, TemplateID, TemplateName, VisitID,'{0}' as DepartmentName  ,'{1}' as PatientName,'{2}' as BedNo , '{3}' as zhuyuanhao ,'{4}' as SEX  FROM [BNNursingDocsSystem_Develop].[dbo].[HealthEduBase](NOLOCK) where PatientID = '{3}' and VisitID ='{5}'";
            sql = string.Format(sql, P.NURSE_CELL_NAME.Trim(), P.PATIENT_NAME.Trim(), P.BED_NO.Trim(), P.PATIENT_ID.Trim(), P.SEX.Trim(), P.VISIT_ID);
            if (Checked == 1)
            {
                string id = "";
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    value = gridView1.GetDataRow(i)["勾选"].ToString();
                    if (value == "True")
                    {
                        id = gridView1.GetDataRow(i)["id"].ToString();
                    }
                }
                sql += string.Format("and (id = '{0}')", id.Trim());
            }
            if (Checked > 1 && Checked < gridView1.RowCount)
            {
                string[] idArray = new string[Checked];
                for (int i = 0, j = 0; i < gridView1.RowCount; i++)
                {
                    value = gridView1.GetDataRow(i)["勾选"].ToString();
                    if (value == "True")
                    {
                        idArray[j] = gridView1.GetDataRow(i)["id"].ToString();
                        j++;
                    }
                }
                sql += string.Format("and ((id = '{0}')", idArray[0].Trim());
                for (int i = 1; i < Checked; i++)
                {
                    sql += string.Format("OR (id = '{0}')", idArray[i].Trim());
                }
                sql += ")";
            }
            sql += "ORDER BY EduDate";
            DataTable x = SqlHelper.ExecuteDataset(sql, CommandType.Text).Tables[0];
            List<HealthEduBase> edulist = new List<HealthEduBase>();
            for (int i = 0; i < x.Rows.Count; i++)
            {
                HealthEduBase xx = new HealthEduBase();
                xx.BedNo = x.Rows[i]["BedNo"].ToString();
                xx.ClassGuid = x.Rows[i]["ClassGuid"].ToString();
                xx.ClassName = x.Rows[i]["ClassName"].ToString();
                xx.DepartmentName = P.NURSE_CELL_NAME;
                xx.EduDate = Convert.ToDateTime(x.Rows[i]["EduDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
                xx.EduNurse = x.Rows[i]["EduNurse"].ToString();
                xx.PatientId = x.Rows[i]["PatientId"].ToString();
                xx.PatientName = x.Rows[i]["PatientName"].ToString();
                xx.ProjectName = x.Rows[i]["ProjectName"].ToString();
                xx.SEX = x.Rows[i]["SEX"].ToString();
                xx.VisitID = x.Rows[i]["VisitID"].ToString();
                xx.Insert = false;
                edulist.Add(xx);
            }
            int count = edulist.Count;
            if (count == 0) return;
            BigHealthEduBase bigbase = NewBigHealthEduBase(edulist[0]);
            List<BigHealthEduBase> tempbig = new List<BigHealthEduBase>();
            if (count == 1) tempbig.Add(bigbase);
            int insert = 0;
            for (int i = 1; i < count; )
            {
                if (edulist[i].Insert != true) //这条没被和
                {
                    for (int j = i; j < count; j++)
                    {
                        if (edulist[j].ProjectName == bigbase.ProjectName)  //可以和
                        {
                            if (bigbase.Number == 1) //bigbase中只有1条
                            {
                                bigbase.EduDate2 = edulist[j].EduDate;
                                bigbase.EduNurse2 = edulist[j].EduNurse;
                                edulist[j].Insert = true;
                                bigbase.Number++;
                                insert++;
                                continue;
                            }
                            if (bigbase.Number == 2)//bigbase中已有2条
                            {
                                bigbase.EduDate3 = edulist[j].EduDate;
                                bigbase.EduNurse3 = edulist[j].EduNurse;
                                edulist[j].Insert = true;
                                bigbase.Number++;
                                insert++;
                                tempbig.Add(bigbase);
                            aa:
                                if (i < count)
                                {
                                    if (edulist[i].Insert == false)
                                    {
                                        bigbase = NewBigHealthEduBase(edulist[i]);
                                        j = i;
                                    }
                                    else
                                    {
                                        i++;
                                        goto aa;
                                    }

                                }
                                else // i走完了 无法创建新的bigbase
                                {
                                    i = count;  //结束所有
                                }
                            }
                        }
                        else //不可以和 默认j++
                        {
                            if (j == count - 1) //j走到最后都不能和
                            {
                                tempbig.Add(bigbase);//创建新bigbase                            
                            bb:
                                if (i < count)
                                {

                                    if (edulist[i].Insert == false)
                                    {
                                        bigbase = NewBigHealthEduBase(edulist[i]);
                                    }
                                    else
                                    {
                                        i++;
                                        goto bb;
                                    }
                                }
                                else // i走完了 无法创建新的bigbase
                                {
                                    i = count;  //结束所有
                                }
                            }
                        }
                    }
                }
                i++;
            }
            if (ifsame(bigbase, tempbig) == false)
            {
                tempbig.Add(bigbase);
            }
            string del_sql = " delete [BNNursingDocsSystem_Develop].[dbo].[HealthEduPrint] where  PatientID ='{0}' and VisitID ='{1}'";
            del_sql = string.Format(del_sql, P.PATIENT_ID.Trim(), P.VISIT_ID);
            SqlHelper.ExecuteNonQuery(CommandType.Text, del_sql);
            for (int i = 0; i < tempbig.Count; i++)
            {
                string insert_sql = @" insert into [BNNursingDocsSystem_Develop].[dbo].[HealthEduPrint] ([DepartmentName] ,[ClassName] ,[ProjectName] ,[PatientName] ,[PatientID] ,[VisitID] ,[BedNo] ,[EduDate1] ,[EduDate2] ,[EduDate3] ,[EduNurse1] ,[EduNurse2] ,[EduNurse3] ,[Number] ,[SEX] ) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}')";
                insert_sql = string.Format(insert_sql, tempbig[i].DepartmentName, tempbig[i].ClassName, tempbig[i].ProjectName, tempbig[i].PatientName, tempbig[i].PatientId, tempbig[i].VisitID, tempbig[i].BedNo, tempbig[i].EduDate1, tempbig[i].EduDate2, tempbig[i].EduDate3, tempbig[i].EduNurse1, tempbig[i].EduNurse2, tempbig[i].EduNurse3, tempbig[i].Number, tempbig[i].SEX);
                SqlHelper.ExecuteNonQuery(CommandType.Text, insert_sql);
            }
            if (CmbPrintTemp.SelectedIndex < 0) { XtraMessageBox.Show("请选择模板"); return; }
            string DiseasesGuid = PrintTempList[CmbPrintTemp.SelectedIndex]["DiseasesGuid"].ToString();
            string edu_sql = getEduData(tempbig[0].PatientId, P.PATIENT_NAME, P.BED_NO, P.NURSE_CELL_NAME, tempbig[0].VisitID, DiseasesGuid);
            //旧的打印
            HealthEduPrint eduPrint = new HealthEduPrint(edu_sql);
            //新的打印
            //HealthEduPrints eduPrint = new HealthEduPrints(edu_sql);
            eduPrint.FormBorderStyle = FormBorderStyle.FixedSingle; //隐藏子窗体边框（去除最小花，最大化，关闭等按钮）
            eduPrint.TopLevel = true; //指示子窗体非顶级窗体
            eduPrint.Show();
        }
        //健康宣教报表打印页数计算
        public int selectPageSize(string PatientID, string VisitID = "", string DiseasesGuid = "")
        {
            PatientID = PatientID.Trim();
            string sql = "select NUM=(select (case when MAX(num)%3 >0 then (MAX(num)/3)+1 else (MAX(num)/3) end) as NUM from (select ProjectGuid,count(id) as num  from HealthEduBase(NOLOCK)  where PatientID='{0}'";
            sql = string.Format(sql, PatientID);
            if (!string.IsNullOrWhiteSpace(VisitID))
            {
                sql = sql + " and VisitID=" + VisitID;
            }
            if (!string.IsNullOrEmpty(DiseasesGuid))
            {
                sql = sql + "and DiseasesGuid ='" + DiseasesGuid + "'";
            }
            else
            {
                sql = sql + "and DiseasesGuid in(select top(1) DiseasesGuid from HealthEduBase(NOLOCK)  where PatientID='" + PatientID + "'";
                if (!string.IsNullOrWhiteSpace(VisitID))
                {
                    sql = sql + " and VisitID=" + VisitID;
                }
                sql = sql + " order by id desc)";
            }
            sql = sql + "   group by ProjectGuid) as m )  from HealthEduClass c,HealthEduProject p   where c.ClassGuid=p.ClassGuid  and c.DiseasesGuid in(select top(1) DiseasesGuid from HealthEduBase(NOLOCK)  where PatientID='" + PatientID + "'";
            if (!string.IsNullOrWhiteSpace(VisitID))
            {
                sql = sql + " and VisitID=" + VisitID;
            }
            sql = sql + "  order by id desc)";
            string num = SqlHelper.ExecuteDataset(sql, CommandType.Text).Tables[0].Rows[0]["NUM"].ToString();
            return !string.IsNullOrEmpty(num) ? int.Parse(num) : 0;
        }

        //获取报表打印数据
        public string getEduData(string PatientID, string xingming, string BedNo, string DepartmentName, string VisitID = "", string DiseasesGuid = "")
        {
            int pageCount = selectPageSize(PatientID, VisitID, DiseasesGuid);
            string page = pageCount == 0 ? "3" : (pageCount * 3) + "";
            string yiyuan = "泉州市第一医院";
            string sql = string.Format(@"declare @Hospital nvarchar(50)
										 declare @PatientID nvarchar(50)
										 declare @VisitID int
										 declare @PatientName nvarchar(50)
										 declare @Page int
										 declare @DepartmentName nvarchar(50)
										 declare @BedNo nvarchar(50)
										 declare @DiseasesGuid nvarchar(50)
										 set @Hospital='{0}'
										 set @PatientID='{1}'
										 set @PatientName='{2}'
										 set @Page={3}
										 set @DepartmentName='{4}'
										 set @BedNo='{5}'
										 set @VisitID={6}
										 set @DiseasesGuid='{7}'
										 select zhuyuanhao=@PatientID,xingming=@PatientName, page=@Page, yiyuan=@Hospital , DepartmentName=@DepartmentName
										,BedNo=@BedNo , a.* , b.EduDate,b.EduDate as EduDate1 ,b.EduNurse,b.PatientID,b.PatientName 
										from 
										(  select  ROW_NUMBER() OVER(PARTITION BY t.ProjectGuid ORDER BY t.ProjectGuid) AS cou
										   , t.* from 
										   (select c.id as cid,p.id as pid,c.Class,c.ClassGuid,p.ProjectName,p.ProjectGuid ,NUM=@Page
											  ,c.OrderNum as order1,p.id as order2 from HealthEduClass c(NOLOCK),HealthEduProject p(NOLOCK)   
											  where c.ClassGuid=p.ClassGuid  
											  and c.DiseasesGuid=@DiseasesGuid 
										   )t
										   , (select number from master..spt_values where number between 1 
											  and (
													select max(NUM) from 
													  (
														select c.Class,c.ClassGuid,p.ProjectName,p.ProjectGuid ,NUM=@Page
														from HealthEduClass c,HealthEduProject p   
														where c.ClassGuid=p.ClassGuid  
														--and c.DiseasesGuid =@DiseasesGuid
													  )t
												  ) and type='P'
										  ) t2  
										)a   
										left join 
										( select  ROW_NUMBER() OVER(PARTITION BY ProjectGuid ORDER BY EduDate) AS cou ,ProjectGuid,EduDate
													,EduNurse,PatientID,PatientName,ProjectContentID from HealthEduBase(NOLOCK) where PatientID=@PatientID and VisitID=@VisitID  
													and DiseasesGuid=@DiseasesGuid 
										)b  
										on a.cou=b.cou  and a.ProjectGuid=b.ProjectGuid    
										where 1=1 --a.cou between @Start and @End  
										order by 
											  (
											  select top 1 OrderNum from HealthEduClass(NOLOCK) 
											  where ClassGuid=a.ClassGuid
											  )
											  ,(
												 select top 1 OrderNum from HealthEduProject(NOLOCK) 
												 where ProjectGuid=a.ProjectGuid
											   )
											  ,a.order1
											  ,b.ProjectContentID
											  ,case when b.EduDate is null then '2099-01-01 00:00:00' else b.EduDate end", yiyuan, PatientID, xingming, page, DepartmentName, BedNo, VisitID, DiseasesGuid);
            WriteLog.WriteLogString(sql);
            return sql;
        }
        #endregion

        #region 刷新事件
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            BindInfo();
        }
        #endregion

        bool ifsame(BigHealthEduBase x, List<BigHealthEduBase> xx)
        {
            if (xx.Count <= 0) return false;
            if (x.ProjectName == xx[xx.Count - 1].ProjectName && x.EduDate1 == xx[xx.Count - 1].EduDate1 && x.EduDate2 == xx[xx.Count - 1].EduDate2 && x.EduNurse1 == xx[xx.Count - 1].EduNurse1)
            {
                return true;
            }
            else return false;
        }

        BigHealthEduBase NewBigHealthEduBase(HealthEduBase xx)
        {
            BigHealthEduBase BigHealthEduBase = new BigHealthEduBase();
            BigHealthEduBase.BedNo = xx.BedNo;
            BigHealthEduBase.ClassGuid = xx.ClassGuid;
            BigHealthEduBase.ClassName = xx.ClassName;
            BigHealthEduBase.DepartmentName = xx.DepartmentName;
            BigHealthEduBase.EduDate1 = xx.EduDate;
            BigHealthEduBase.EduNurse1 = xx.EduNurse;
            BigHealthEduBase.Number = 1;
            BigHealthEduBase.PatientId = xx.PatientId;
            BigHealthEduBase.PatientName = xx.PatientName;
            BigHealthEduBase.ProjectName = xx.ProjectName;
            BigHealthEduBase.SEX = xx.SEX;
            BigHealthEduBase.VisitID = xx.VisitID;
            xx.Insert = true;
            return BigHealthEduBase;
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {
            Point pt = gridControl1.PointToClient(MousePosition);
            GridHitInfo info = gridView1.CalcHitInfo(pt);
            if (info.Column == null) return;
            if (info.Column.ToString() == "分类")
            {
                if (info.RowHandle >= 0)
                {
                    string classname = gridView1.GetDataRow(info.RowHandle)["ClassName"].ToString();
                    if (gridView1.GetDataRow(info.RowHandle)["勾选"].ToString() == "True")
                    {
                        for (int i = 0; i < gridView1.RowCount; i++)
                        {
                            if (gridView1.GetDataRow(i)["ClassName"].ToString() == classname)
                            {
                                gridView1.SetRowCellValue(i, gridView1.Columns[0], false);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < gridView1.RowCount; i++)
                        {
                            if (gridView1.GetDataRow(i)["ClassName"].ToString() == classname)
                            {
                                gridView1.SetRowCellValue(i, gridView1.Columns[0], true);
                            }
                        }
                    }
                }
            }
            if (!info.InRowCell && info.Column.AbsoluteIndex == 0)//Index判断用于哪一列的列头
            {
                string value;
                int Checked = 0;
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    value = gridView1.GetDataRow(i)["勾选"].ToString();
                    if (value == "True")
                    {
                        Checked++;
                    }
                }
                if (Checked == 0)
                {
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        gridView1.SetRowCellValue(i, gridView1.Columns[0], true);
                    }
                }
                else
                {
                    for (int i = 0; i < gridView1.RowCount; i++)
                    {
                        gridView1.SetRowCellValue(i, gridView1.Columns[0], false);
                    }
                }
            }
        }
    }
}